#include <iostream>
#include <string>
#include <string.h>
#include <mysql/mysql.h>
using namespace std;

#define HOST "127.0.0.1"
#define USER "root"
#define PASS "LJb147258"
#define DBNAME "test1"
#define PORT 3306


int main()
{
    MYSQL* mysql = mysql_init(nullptr);
    if(mysql == nullptr)
    {
        cout << "mysql init fail" << endl;
        return -1;
    }

    if(mysql_real_connect(mysql,HOST,USER,PASS,DBNAME,PORT,nullptr,0) == nullptr)
    {
        cout << "connect mysql server failed: " << mysql_errno(mysql) << endl;
        mysql_close(mysql);
        return -1;
    }

    if(mysql_set_character_set(mysql,"utf8") != 0)
    {
        cout << "set client character failef: " << mysql_errno(mysql) << endl;
        mysql_close(mysql);
        return -1;
    }

    //mysql_select_db(mysql,DBNAME);

    // string sq1 = "insert stu values(null,'小明',18,53,68,87);";
    // int ret = mysql_query(mysql,sq1.c_str());

    // string sq1 = "update stu set ch=ch+40 where sn=1;";
    // int ret = mysql_query(mysql,sq1.c_str());

    // string sq1 = "delete from stu where sn=2;";
    // int ret = mysql_query(mysql,sq1.c_str());

    string sq1 = "select * from stu;";
    int ret = mysql_query(mysql,sq1.c_str());

    if(ret != 0)
    {
        cout << sq1 << endl;
        cout << "mysql query failef: " << mysql_errno(mysql) << endl;
        mysql_close(mysql);
        return -1;
    }

    MYSQL_RES*  res = mysql_store_result(mysql);
    if(res == nullptr)
    {
        cout << "mysql store result failef: " << mysql_errno(mysql) << endl;
        mysql_close(mysql);
        return -1;
    }

    int num_row = mysql_num_rows(res);
    int num_col = mysql_num_fields(res);

    for(int i = 0; i < num_row; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < num_col; j++)
        {
            cout << row[j] << '\t';
        }
        cout << endl;
    }

    mysql_free_result(res);

    mysql_close(mysql);
    return 0;
}


